<template>
  <div class="specifications app-container">
    <header>
      <el-row class="my-table-header">
        <div style="flex: 0 0 16.6666666667%; padding-left: 18px">分类预览名称</div>
        <div class="tags">规格名称</div>
        <div style="text-align: center; flex: 1">排序</div>
        <div style="text-align: center; flex: 1">状态</div>
        <div class="action" style="text-align: center">操作</div>
      </el-row>
    </header>

    <el-container ref="myTableRef2" class="my-el-container">
      <el-aside>
        <div class="aside-wrap" v-loading="loadingLeft">
          <el-tree
            style="max-width: 600px"
            :data="classifyList"
            :props="{ label: 'name', children: 'children' }"
            node-key="categoryId"
            highlight-current
            accordion
            :expand-on-click-node="true"
            :current-node-key="currentNodeKey"
            @node-click="handleNodeClick"
          />
        </div>
      </el-aside>
      <el-container>
        <el-header>
          <p>{{ classifyTitle }}</p>
          <div style="display: flex">
            <el-button type="primary" size="small" :icon="Plus" @click="clickAddOrEdit({}, 'add')">添加规格</el-button>
            <el-button type="primary" size="small" @click="clickCopy(tableData, 'all')">复制全部</el-button>
            <el-button type="primary" size="small" @click="clickPaste" plain>粘贴</el-button>
          </div>
        </el-header>
        <el-main :style="{ height: `calc(100vh - ${tableTop}px - 70px)` }">
          <el-table
            v-loading="loading"
            :data="tableData"
            style="width: 100%; margin-bottom: 20px"
            row-key="specificationId"
            :show-header="false"
            border
            default-expand-all
          >
            <el-table-column prop="name" label="name" class-name="tags" width="300" />
            <el-table-column prop="sortOrder" label="sortOrder" class-name="sort">
              <template #default="scope">
                <el-input
                  v-if="scope.row.format ? scope.row.format.split('-').length !== 3 : false"
                  type="number"
                  v-model="scope.row.sortOrder"
                  min="1"
                  @change="debounceChangeSort(scope.row, $event)"
                />
                <span v-else>--</span>
              </template>
            </el-table-column>
            <el-table-column prop="status" label="status" class-name="status cell-center">
              <template #default="scope">
                <el-tag v-if="scope.row.status === 1 && scope.row.format.split('-').length === 1">显示</el-tag>
                <el-tag v-else-if="scope.row.status === 0" type="info">禁用</el-tag>
                <el-button v-else :type="'primary'" link style="width: 34px">--</el-button>
              </template>
            </el-table-column>
            <el-table-column prop="actin" label="操作" class-name="action" width="200">
              <template #default="scope">
                <div class="btn-wrap">
                  <!-- 添加 -->
                  <el-button
                    v-if="scope.row.format ? scope.row.format.split('-').length === 1 && scope.row.levelType === 1 : false"
                    :type="'primary'"
                    link
                    @click="clickAddOrEdit(scope.row, 'add')"
                    >添加</el-button
                  >
                  <el-button v-else :type="'primary'" link style="width: 34px">--</el-button>

                  <!-- 复制 -->
                  <el-button
                    v-if="scope.row.format ? scope.row.format.split('-').length === 1 : false"
                    :type="'primary'"
                    link
                    @click="clickCopy(scope.row, 'part')"
                    >复制</el-button
                  >
                  <el-button v-else :type="'primary'" link style="width: 34px">--</el-button>

                  <el-button :type="'primary'" link @click="clickAddOrEdit(scope.row, 'edit')">编辑</el-button>
                  <el-button
                    :type="'primary'"
                    link
                    @click="
                      () => {
                        currObj = scope.row;
                        _isOpen = true;
                      }
                    "
                    >删除</el-button
                  >
                </div>
              </template>
            </el-table-column>
          </el-table>
        </el-main>
      </el-container>
    </el-container>

    <!-- 删除时的二次确认框 -->
    <ActionSubmitDialog
      v-model:isOpen="_isOpen"
      :message="'温馨提示： 操作此选项后，该商品规格将会被永久删除，确认删除操作吗？'"
      @submit="returnSubmit"
    />

    <AddForm :optionInfo="optionInfoAdd" @close="addClose" @submit="addSubmit"></AddForm>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick, watch } from "vue";
import { Plus } from "@element-plus/icons-vue";
import AddForm from "./components/AddForm";
import { getStastsList, saveOrEditStasts, deleteStasts, copyStasts } from "@/api/products/attribute";
import { getSpecificationList, saveSpecification, deleteSpecification, copySpecification } from "@/api/products/specifications";
import { _throttle } from "@/utils/index";
import { ElMessage, ElNotification } from "element-plus";
import useClassifyStore from "@/store/modules/classify";
const classifyStore = useClassifyStore();
import { orgChildIdFindParent } from "@/utils/index";
import ActionSubmitDialog from "@/components/ActionSubmitDialog";

const loading = ref(false);
const tableData = ref([]);
const tableTop = ref(0);
const myTableRef2 = ref();
const optionInfoAdd = ref({ isShow: false, type: "add", formData: {} });
const classifyList = ref([]);
const currentNodeKey = ref(""); //1780859823072493568
const currentNode = ref({});
const currObj = ref({});
const _isOpen = ref(false);

onMounted(async () => {
  setTimeout(() => {
    console.log(9090909, myTableRef2.value.$el.getBoundingClientRect().top);
    tableTop.value = myTableRef2.value.$el.getBoundingClientRect().top;
  }, 0);
  await getClassifyList();
});

watch(
  () => currentNodeKey.value,
  () => {
    getList();
  },
  { deep: true, immediate: false }
);

// 确认删除操作
const returnSubmit = () => {
  clickDel(currObj.value);
};

const loadingLeft = ref(false);
// 查询分类tree
const getClassifyList = async () => {
  loadingLeft.value = true;
  const List = await classifyStore.getList({ searchkey: "" });
  loadingLeft.value = false;
  classifyList.value = List;
  nextTick(() => {
    const firstLeafNode = findFirstLeafNode(List); //第一个叶子节点
    currentNode.value = firstLeafNode;
    currentNodeKey.value = firstLeafNode.categoryId;
    setlevelName(firstLeafNode.categoryId, classifyList.value, "categoryId");
  });
};

const findFirstLeafNode = tree => {
  // 定义递归函数 traverse，用于深度搜索树的每个节点
  function traverse(node) {
    // 如果当前节点为叶子节点，即没有子节点，则返回该节点
    if (!node.children || node.children.length === 0) {
      return node;
    }
    // 如果当前节点有子节点，则遍历每个子节点，继续递归调用 traverse 函数
    for (const child of node.children) {
      const result = traverse(child);
      // 如果在子节点中找到了第一个叶子节点，则立即返回该节点
      if (result) {
        return result;
      }
    }
  }

  // 外部循环遍历树的根节点
  for (const node of tree) {
    // 对于每个根节点，都调用 traverse 函数来查找第一个叶子节点
    const result = traverse(node);
    // 如果在当前根节点下找到了第一个叶子节点，则立即返回该节点
    if (result) {
      return result;
    }
  }
  return null;
};

const classifyTitle = ref("");
const setlevelName = (id, tree, key) => {
  const parentsArr = orgChildIdFindParent(id, tree, key);
  const parentNameArr = parentsArr.map(item => {
    return item.name;
  });
  parentNameArr.push(currentNode.value.name); //加入当前选中的分类名称
  classifyTitle.value = parentNameArr.join("-");
  // console.log("找到了父级===", parentsArr);
};
// 选中分类tree的节点
const handleNodeClick = (item, node, treeNode, event) => {
  // console.log("选中分类tree的节点===", item);
  if (!node.isLeaf) return;
  currentNode.value = item;
  currentNodeKey.value = item.categoryId;
  setlevelName(item.categoryId, classifyList.value, "categoryId");
};

const getList = () => {
  loading.value = true;
  getSpecificationList({ categoryId: currentNodeKey.value })
    .then(res => {
      if (res.code === 200) {
        tableData.value = res.data;
      } else {
        ElMessage({
          message: res.msg,
          type: "error"
        });
      }
      loading.value = false;
    })
    .catch(err => {
      ElMessage({
        message: err,
        type: "error"
      });
      loading.value = false;
    });
};

const debounceChangeSort = _throttle((item, event) => {
  // console.log("更改排序");
  const parentsArr = orgChildIdFindParent(item.specificationId, tableData.value, "specificationId");
  let DATA = treeRecursion([item], { type: "2" });
  DATA[0].sortOrder = event;
  let LIST = null;
  if (item.format.split("-").length === 2) {
    LIST = [
      {
        ...parentsArr[0],
        children: DATA
      }
    ];
  } else if (item.format.split("-").length === 1) {
    LIST = DATA;
  }

  saveSpecification({ categoryId: LIST[0].categoryId, list: LIST }).then(res => {
    if (res.code === 200) {
      ElMessage({
        message: "排序修改成功",
        type: "success"
      });
      getList();
    }
  });
}, 3000);

//点击删除
const clickDel = item => {
  deleteSpecification({ specificationId: item.specificationId }).then(res => {
    if (res.code === 200) {
      ElMessage({
        message: "删除成功",
        type: "success"
      });
      getList();
      _isOpen.value = false;
    }
  });
};

//点击添加、编辑
const clickAddOrEdit = (item, type) => {
  console.log("点击添加===", tableData.value);
  optionInfoAdd.value.isShow = true;
  optionInfoAdd.value.type = type;
  optionInfoAdd.value.formData = item;
  optionInfoAdd.value.list = tableData.value;
  optionInfoAdd.value.currentClassNode = [{ ...currentNode.value, children: [] }];
  optionInfoAdd.value.classifyTitle = classifyTitle.value;
};
const addClose = () => {
  optionInfoAdd.value.isShow = false;
};

//确认添加、编辑，组件的submit回调
const addSubmit = (data, type = "add", level) => {
  const formData = JSON.parse(JSON.stringify(data));
  console.log("这是组件传递过来的表单数据===", formData);
  optionInfoAdd.value.isShow = false;
  let DATA = treeRecursion(formData, { type: "2" });
  if (type === "add") {
    saveSpecification({ categoryId: currentNodeKey.value, list: formData }).then(res => {
      if (res.code === 200) {
        getList();
      }
    });
  } else {
    saveSpecification({ categoryId: formData[0].categoryId, list: formData }).then(res => {
      if (res.code === 200) {
        getList();
      }
    });
  }
};

// 点击复制
/**
 *
 * @param {*} data
 * @param {*} type part-部分   all-全部
 */
const clickCopy = (data, type) => {
  let DATA = JSON.parse(JSON.stringify(data));
  if (type === "part") {
    DATA = [DATA];
  }
  localStorage.setItem("copyListTreeSpe", JSON.stringify(DATA));
  ElNotification({
    title: "通知",
    message: "复制成功！请前往粘贴添加！",
    duration: 3000,
    type: "success",
    offset: 50
  });
};
// 点击粘贴
const clickPaste = () => {
  if (!localStorage.getItem("copyListTreeSpe")) {
    ElMessage({
      message: "请先复制数据，再进行粘贴",
      type: "error"
    });
    return;
  }

  let DATA = treeRecursion(JSON.parse(localStorage.getItem("copyListTreeSpe")), {}, "upd"); //重命名，统一加一个copy

  copySpecification({ categoryId: currentNodeKey.value, list: DATA }).then(res => {
    if (res.code === 200) {
      getList();
      localStorage.removeItem("copyListTreeSpe");
    }
  });
};

//递归遍历tree，添加、修改属性键值对
const treeRecursion = (data, keyValue = { type: "2" }, type = "add") => {
  if (type === "add") {
    data = data.map(item => {
      return {
        ...item, // 如果想在原数组添加属性
        ...keyValue,
        children: item.children && item?.children.length > 0 ? treeRecursion(item.children, keyValue) : item.children // 判断当前是否还有子节点
      };
    });
    return data;
  } else {
    const key = Object.keys(keyValue)[0];
    data = data.map(item => {
      const obj = {
        ...item, // 如果想在原数组添加属性
        specificationId: ""
      };
      console.log(909090, item[key], key);
      obj[key] = item[key] + keyValue[key];
      obj.children = item.children && item?.children.length > 0 ? treeRecursion(item.children, keyValue, type) : item.children; // 判断当前是否还有子节点
      return obj;
    });
    return data;
  }
};
</script>

<style lang="scss" scoped>
p {
  margin: 0;
}
.specifications {
  :deep(.cell-center) {
    text-align: center !important;
  }
  .my-table-header {
    display: flex;
    .tags {
      width: 300px;
      padding-left: 18px;
    }
    .action {
      width: 200px;
    }
  }
  & > header {
    background-color: #f2f6fc;
    height: 50px;
    line-height: 50px;
    font-size: 14px;
    color: #4e5969;
    margin-left: 8px;
  }
  .my-el-container {
    .el-aside {
      display: flex;
      flex: 0 0 16.6666666667%;
      color: #3d3d3d;
      font-size: 14px;
      margin-bottom: 0;
      background-color: white;
      padding: 10px 8px 8px 8px;
      .aside-wrap {
        width: 100%;
        box-shadow: 0px 0px 8px 0px rgba(4, 19, 74, 0.1);
        p {
          padding: 0 24px;
          line-height: 40px;
          cursor: default;
          &:not(:last-of-type) {
            margin-bottom: 10px;
          }
          &.active {
            background-color: #d9e8ff;
            color: #007dff;
          }
        }
      }
    }
    .el-header {
      background-color: #f5f7fa;
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 0 28px;
      font-size: 14px;
      height: 40px;
      color: #4e5969;
      margin-top: 10px;
    }
    .el-main {
      padding: 0 0 8px 0;
      & > div {
        margin-bottom: 0 !important;
        height: 100%;
      }

      .el-table__row {
        .tags {
          flex: 0 0 20.8333333333%;
        }
      }
    }
  }
}
</style>
